package com.wangjie.simple;

/**
 * @author jieshao
 * @date 2022/5/30 14:17
 *
 * 1979. 找出数组的最大公约数
 */
public class Test10 {
    public static void main(String[] args) {
        int[] nums = {7, 5, 6, 8, 3};
        int res = findGCD(nums);
        System.out.println(res);
    }

    public static int findGCD(int[] nums) {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for (int num : nums) {
            if (num > max) {
                max = num;
            }
            if (num < min) {
                min = num;
            }
        }
        return gcd(max, min);
    }

    /**
     * 辗转相除法(以除数和余数反复做除法运算，当余数为 0 时，取当前算式除数为最大公约数)
     *
     * @param x
     * @param y
     * @return
     */
    public static int gcd(int x, int y) {
        return y == 0 ? x : gcd(y, x % y);
    }
}